import random

from django.shortcuts import render, redirect

# Create your views here.
from django.views import View

from problem.models import Question


def get_point(answer, values):
    point = 0
    check_problem = []
    for index, value in enumerate(values):
        if value is None:
            check_problem.append('false')
            pass
        elif value == answer[index]:
            check_problem.append('true')
            point += 10
        else:
            check_problem.append('false')
    return point, check_problem


class Ques(View):

    def get(self, request):
        # 获取到数据库中所有数据
        all_ques = Question.objects.all().values()
        # 单独获取到题号和对应的正确答案
        all_ques_id = [ques_id['id'] for ques_id in all_ques]
        global question
        question = random.sample(all_ques_id, 10)
        # print(question)
        global cq_question
        cq_question = []
        for item in question:
            cq_question.append(Question.objects.filter(id=item).values())
        full_score = request.GET.get('full_score')
        if full_score == 'true':
            print(full_score)
            return render(request, "ques.html", {'all_ques': cq_question, 'point': 100})
        return render(request, "ques.html", {'all_ques': cq_question})

    def post(self, request):
        get_values = []
        for item in range(1, 11):
            get_values.append(request.POST.get(str(item)))  # post方法获取所以单选的值
        answer_all_list = []
        for item in question:
            answer_all_list.append(Question.objects.filter(id=int(item)).values("true_ans"))  # 通过题目id获取十个题目的正确答案
        answer_all = []
        for answer in answer_all_list:
            answer_all.append(answer[0]['true_ans'])  # 将正确答案添加至列表
        sign = request.POST.get('sign')
        if sign == 'click':
            result, check_problem = get_point(answer_all, get_values)  # 调用计分函数，传入正确答案和用户选项 返回分数
            # print(check_problem)
            if result == 100:  # 分数大于80则优秀，重新刷新题目 小于停留该答题页面
                return redirect('/ques/?full_score=true')
            return render(request, "ques.html", {'all_ques': cq_question, 'point': result, 'get_values': get_values,
                                                 'check_problem': check_problem})
